﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using BitcoinTrading;
using BitcoinTrading.Data;

namespace HaloEffect
{
    public partial class MainFrame : Form
    {
        TradingMain _controller;

        public MainFrame()
        {
            InitializeComponent();

            Initialized();
        }

        private void Initialized()
        {
            _controller = new TradingMain();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            Login();
        }

        private void Login()
        {
            //컨트롤 개체가 생성이 안 되어 있는 경우
            if (_controller == null)
            {
                _controller = new TradingMain();
            }

            //로그인을 한다.
            _controller.Login();

            //로그인 여부를 확인한다.
            if (_controller.IsLogin())
            {
                _controller.RetrievedData();

                lblKorbitLogStatus.Text = "로그인";
                RefreshTokenTime();
                
            }
            else
            {
                lblKorbitLogStatus.Text = "로그아웃";
                lblRefreshTime.Text = "00:00:00";
            }
        }
        
        private void lblInfo_Click(object sender, EventArgs e)
        {
            //로그인이 안 되어 있을 경우 패스한다.
            if (!_controller.IsLogin())
            {
                MessageBox.Show("로그인을 먼저 해주세요.");
                return;
            }

            _controller.RetrievedData();

            GetInfo();

            BindPublicExchangeData();

            //_controller.PassiveClearTrade();
        }


        private void GetInfo()
        {
            //로그인이 안 되어 있을 경우 패스한다.
            if (!_controller.IsLogin())
                return;

            //환율 정보를 받아온다.
            lblCurrency.Text = _controller.CurrentRate().ToString("N02");

            //자산 정보를 받아온다.
            //원화자산
            lblKRWCurrency.Text = _controller.BalanceKorbitKRW().ToString("N02");
            lblKRWBTCAmount.Text = _controller.BalanceKorbitBTC().ToString("N02");
            lblUSDCurrency.Text = _controller.BalanceBTCeUSD().ToString("N02");
            lblUSDBTCAmount.Text = _controller.BalanceBTCeBTC().ToString("N02");

            //전체 자산
            lblKRWCurrencyAsset.Text = lblKRWCurrency.Text;
            lblUSDCurrencyAsset.Text = lblUSDCurrency.Text;
            lblBTCAsset.Text = (_controller.BalanceKorbitBTC() + _controller.BalanceBTCeBTC()).ToString("N02");

            txtActiveMarginalBuy.Text = Double.Parse(_controller.Data().MarginalBuyPrice()).ToString("N0");
            txtActiveMarginalSell.Text = Double.Parse(_controller.Data().MarginalSellPrice()).ToString("N0");

        }

        private void BindPublicExchangeData()
        {
            //데이터 바인딩
            dgvKorbitAsk.DataSource = _controller.Data().KorbitAccAsk() ;
            dgvKorbitBid.DataSource = _controller.Data().KorbitAccBid();
            dgvBTCeAsk.DataSource = _controller.Data().BTCeAccAsk();
            dgvBTCeBid.DataSource = _controller.Data().BTCeAccBid();

        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (btnRun.Text == "매매 시작")
            {
                ActivateTrading();
                btnRun.Text = "매매 중단";
            }
            else
            {
                DeactivateTrading();

                btnRun.Text = "매매 시작";
            }
        }


        private void ActivateTrading()
        {
            if (tmrBase.Enabled == false)
            {
                this.tmrBase.Interval = 10000;
                this.tmrBase.Enabled = true;
            }
        }

        private void DeactivateTrading()
        {
            this.tmrBase.Enabled = false;
        }

        private void ActivateTimer(object sender, EventArgs e)
        {
            RunTrading();
        }

        private void RefreshTokenTime()
        {
            lblRefreshTime.Text = _controller.RefreshTime().ToString("T");
        }

        private void RunTrading()
        {
            _controller.RetrievedData();
            _controller.PassiveTrade();

            _controller.RetrievedData();
            _controller.ActiveTrade();

            RefreshTokenTime();

            GetInfo();

            BindPublicExchangeData();
        }

        private void btnActiveAccept_Click(object sender, EventArgs e)
        {
            string strMarginalBuy;
            string strMarginalSell;

            strMarginalBuy = txtActiveBuy.Text;
            strMarginalSell = txtActiveSell.Text;

            double dbMarginalBuy;
            double dbMarginalSell;

            try
            {
                dbMarginalBuy = Double.Parse(strMarginalBuy);
                dbMarginalSell = Double.Parse(strMarginalSell);

                _controller.ActiveTradeSetMarginalPrice(dbMarginalBuy, dbMarginalSell);

            }catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            
        }

        private void btnOnceMarginalBuy_Click(object sender, EventArgs e)
        {
            bool bReturn;

            bReturn = false;

            try
            {
                bReturn = _controller.ActiveTradeOnceMarginalBuy();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (!bReturn)
                MessageBox.Show("매수차익이 실패하였습니다.");
        }

        private void btnOnceMarginalSell_Click(object sender, EventArgs e)
        {
            bool bReturn;

            bReturn = false;

            try
            {
                bReturn = _controller.ActiveTradeOnceMarginalSell();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (!bReturn)
                MessageBox.Show("매수차익이 실패하였습니다.");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _controller.PassiveClearTrade();
        }

    }
}
